package com.lsp.microorder.pay.config;

import com.alibaba.fastjson.JSON;
import com.lsp.microcommon.entity.DropOrder;
import com.lsp.microorder.pay.param.PayResultParam;
import com.lsp.microorder.pay.service.TradeOrderPayService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;

import javax.annotation.Resource;
import java.io.IOException;

//@Component
//@RabbitListener(queues = "drop_order_queue1")
//@Slf4j
public class DropOrderDelayConsumer {

    @Resource
    private TradeOrderPayService tradeOrderPayService;

    @RabbitHandler
    public void receiveMsg(String msg, Channel channel, Message message){
        DropOrder dropOrder = JSON.parseObject(msg, DropOrder.class);
        try {
//            根据业务订单编号查询交易订单状态，并返回交易订单编号
            String tradeNo = tradeOrderPayService.payStates(dropOrder.getOrderNo(), dropOrder.getPayType());

            PayResultParam param = new PayResultParam();
            param.setPayTradeNo(tradeNo);
            param.setOrderNo(dropOrder.getOrderNo());
            tradeOrderPayService.payFinish(param);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            try {
//                抛弃消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if(dropOrder.getNum().equals(10)){
                tradeOrderPayService.closePay(dropOrder.getOrderNo(),dropOrder.getPayType());
            }else {
                dropOrder.setNum(dropOrder.getNum()+1);
//                再次发送msg
                tradeOrderPayService.sendDropDelayMsg(dropOrder);
            }
        }
    }
}
